<template>
  <div class="w-full h-full">
    <el-container class="h-full">
      <el-header>
        <el-button @click="run">Run</el-button>
      </el-header>
      <el-container>
        <el-aside width="50%">
          <div class="w-full h-1/3">
            <CodeEditor
              ref="html"
              v-model:value="vueTemplate.template"
              language="html"
            ></CodeEditor>
          </div>
          <div class="w-full h-1/3">
            <CodeEditor
              ref="script"
              v-model:value="vueTemplate.script"
              language="javascript"
            ></CodeEditor>
          </div>
          <div class="w-full h-1/3">
            <CodeEditor
              ref="style"
              v-model:value="vueTemplate.style"
              language="css"
            ></CodeEditor>
          </div>
        </el-aside>
        <el-main>
          <div class="w-full h-2/4">
            <component :is="render"></component>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import {
  ComponentInternalInstance,
  getCurrentInstance,
  reactive,
  ref,
} from "vue";
import CodeEditor from "@/components/CodeEditor/index.vue";

const ctx = getCurrentInstance();
const html = ref(null);
const script = ref(null);
const style = ref(null);
const render = ref("v-result");
const key = ref(0);
const vueTemplate = reactive({
  template: "<div class='wa'>111</div>",
  script: "",
  style: ".wa{background:red;}",
});
(ctx as ComponentInternalInstance).appContext.app.component(render.value, {
  template: vueTemplate.template,
});

let styleElement: HTMLStyleElement;
const run = () => {
  // console.log();
  html.value.confirmHandler();
  script.value.confirmHandler();
  style.value.confirmHandler();
  console.log(vueTemplate);
  let service = {};
  try {
    let options = {};
    service = new Function(
      "options",
      vueTemplate.script + ";;return options"
    ).call(null, options);
  } catch (e) {
    console.error(e);
  }
  key.value++;
  render.value = render.value + key.value.toString();
  if (!styleElement) {
    styleElement = document.createElement("style");
    styleElement.id = "result";
    document.head.append(styleElement);
  }

  styleElement.innerHTML = vueTemplate.style;
  (ctx as ComponentInternalInstance).appContext.app.component(render.value, {
    template: vueTemplate.template,
    ...service,
  });
  // setTimeout(() => {
  //   key.value++;
  // }, 1000);
  // console.log(vueTemplate);
};
</script>

<style scoped></style>
